package com.spzx.product.message;


import com.rabbitmq.client.Channel;
import com.spzx.common.core.utils.StringUtils;
import com.spzx.common.rabbit.constant.MqConst;
import com.spzx.common.security.utils.SecurityUtils;
import com.spzx.product.service.SkuStockService;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class SkuStockReceiver {

    @Autowired
    private SkuStockService skuStockService;


    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(value = MqConst.EXCHANGE_PRODUCT),
            value = @Queue(value = MqConst.QUEUE_UNLOCK),
            key = MqConst.ROUTING_UNLOCK
    ))
    public void unLock(String trodeNo, Message message, Channel channel){
        //判断交易号是否为空
        if (StringUtils.hasText(trodeNo)){
            try {
                //调用SkuStockService中解锁库存的方法
                skuStockService.unLockStocl(trodeNo);
                //处理完业务逻辑,手动确认消费了消息
                channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
            } catch (Exception e) {
                //throw new RuntimeException(e);
                try {
                    //出现异常,将消息放回原队列
                    channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,true);
                } catch (IOException ex) {
                    throw new RuntimeException(ex);
                }
            }

        }

    }

}
